<?php

namespace app\api\job;

use app\admin\controller\KingAction;
use app\common\model\ApplicationBanker;
use app\common\model\BetsLog;
use app\common\model\GamblerKing;
use app\common\model\GamesLog;
use app\common\model\KingAccountLog;
use app\common\model\KingBalanceLog;
use app\common\model\LotteryPlay;
use app\common\model\PlanUserProgramme;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use think\Db;
use think\queue\Job;

class Consumer
{

    public function fire(Job $job, $data)
    {
        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if (!$isJobStillNeedToBeDone) {
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone == 'success') {
            // 如果任务执行成功， 记得删除任务
            $job->delete();

//            print("<info>Hello Job has been done and deleted"."</info>\n");
        } else {
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
//                print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");

                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data)
    {
        return true;
    }

    public static function getMillisecond()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime, 0, 13);
    }

    private function doHelloJob($data)
    {


//        return true;

        Db::startTrans();
        $bets = BetsLog::get(['trade_no' => $data]);
        if (!$bets) {
            d('没有');
            return true;
        }
        if ($bets['state'] == 4) {
            d('没有状态');
            return true;
        }
//
        $money = ['2-1' => 1, '0.2-1' => 2, '0.02-1' => 3, '0.002-1' => 4, '1-1' => 5, '0.1-1' => 6, '0.01-1' => 7];
        if (empty($money[$bets['univalent'].'-1'])) {
            $bets['mult'] = $bets['univalent'] / 2;
            $bets['univalent'] = 2;
        }

        try {
            $app_info = ApplicationBanker::get(1);
            if($app_info['status']!=1){
                d('庄家投注已关闭');
                return true;
            }
            $bet = BetsLog::get(['trade_no' => $data]);
            $res = $this->third_bets($data);


            d($res);
            if (!$res) {
                d('第三方错误');
                //撤单
                $user_account = UserAccount::check(['user_id' => $bet['user_id'], 'wallet_id' => 1], false);

                $user_account->balance += $bet['money'];
                $user_account->save();
                //写入流水
                UserAccountLog::create([
                    'user_id' => $bet['user_id'],
                    'wallet_id' => 1,
                    'before_blance' => $user_account->balance - $bet['money'],
                    'after_blance' => $user_account->balance,
                    'remark' => '下注失败退回',
                    'is_add' => 1,
                    'number' => $bet['money'],
                    'type' => 31,
                ]);
                if ($bet['programme_id'] > 0) {
                    PlanUserProgramme::where(['id' => $bets['programme_id']])->setDec('current_round', 1);
                }

                $arr = [
                    'order_no' => $data,
                    'state' => 6,
                    'type' => 1,
                    'app_id' => $app_info['id'],
                    'create_time' => TIME_NOW,
                    'user_id' => $bets['user_id'],
                    'number' => $bet['money'],
                    'entrust_count' => $bet['entrust_count'],
                    'remark' => '第三方接口请求失败撤单',
                ];
                if($bets->play_id==5 && $bets->injection_number==5 && $bets['mult']%2==0){
                    $arr['number']=$arr['number']/2;
                }
                GamesLog::where(['order_no' => $bet['trade_no']])->delete();
                $arr['bet_username'] = $app_info['username'];
                $arr['king_number'] = format_money(($app_info['return_point'] - $bet->user->level->game_return) / 100 * $bet->money, 2);
                $arrs[] = $arr;
                GamesLog::insertAll($arrs);
                $bet->state = 4;
                $bet->save();

                // 提交事务
                Db::commit();
                return true;
            }

            if ($res['code'] != 0) {

                //失败
                $state = 6;

            } else {
                $state = 1;
            }



            if ($state == 6) {
                $bet->state = 4;
                $bet->save();

                GamesLog::where(['order_no' => $bet['trade_no']])->delete();
                if ($bet['king_id'] > 0) {
                    $king = GamblerKing::where(['id' => $bet['king_id']])->lock(true)->find();


                    $king->king_win_account += $bet['money'];
                    KingBalanceLog::create([
                        'user_id' => $bet['user_id'],
                        'king_id' => $bet['king_id'],
                        'number' => $bet['money'],
                        'remark' => '下注失败退回',
                        'is_add' => 1,
                        'type' => 1
                    ]);

                    $king->save();


                } else {
                    //撤单
                    $user_account = UserAccount::check(['user_id' => $bet['user_id'], 'wallet_id' => 1], false);

                    $user_account->balance += $bet['money'];
                    $user_account->save();
                    //写入流水
                    UserAccountLog::create([
                        'user_id' => $bet['user_id'],
                        'wallet_id' => 1,
                        'before_blance' => $user_account->balance - $bet['money'],
                        'after_blance' => $user_account->balance,
                        'remark' => '下注失败退回',
                        'is_add' => 1,
                        'number' => $bet['money'],
                        'type' => 31,
                    ]);

                }
                if ($bet['programme_id'] > 0) {
                    PlanUserProgramme::where(['id' => $bets['programme_id']])->setDec('current_round', 1);
                }

            }

            $arr = [
                'order_no' => $data,
                'state' => $state,
                'type' => 1,
                'app_id' => $app_info['id'],
                'create_time' => TIME_NOW,
                'user_id' => $bets['user_id'],
                'number' => $bet['money'],
                'entrust_count' => $bet['entrust_count'],
                'remark' => $res['message'],

            ];

            if($bets->play_id==5 && $bets->injection_number==5 && $bets['mult']%2==0){
                $arr['number']=$arr['number']/2;
            }
            $arr['bet_username'] = $app_info['username'];
            $arr['king_number'] = format_money(($app_info['return_point'] - $bet->user->level->game_return) / 100*0.05 * $arr['number'], 2);
            $arrs[] = $arr;
            GamesLog::insertAll($arrs);


            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            d($e->getMessage());
            // 回滚事务
            Db::rollback();
            return false;

        }


    }


    /**
     * 第三方下注
     */

    public function third_bets($data)
    {
        $arrs = $arr1s = [];
        $bets = BetsLog::get(['trade_no' => $data]);

        $app_info = ApplicationBanker::get(1);
        $lottery = $bets->lottery;
        $cate_symbol = $lottery->cate->symbol;

        if ($bets['is_old'] == 1) {
            $bets['class2'] = LotteryPlay::where(['id' => $bets['play_id']])->value('name');

        }
        $bets['playid'] = $bets->play->symbol;
        $bets['univalent'] = floatval($bets['univalent']);
        if($bets->play_id==5 && $bets->injection_number==5 && $bets['mult']%2==0){
            $bets['mult'] =$bets['mult']/2;
            $bets['money'] =$bets['money']/2;
            if($bets->user->is_just==2){
                $bets['number']=$bets['inverse_code'];
            }
        }
        $arrs[] = $bets;

        if ($bets['is_old'] == 1) {

            include_once(ROOT_PATH . 'extend/thirdparty/oldplay.php');
            $_zhushuyzclass = "thirdparty\\oldplay";
            $_obj = new $_zhushuyzclass($arrs);

        } else {
            include_once(ROOT_PATH . 'extend/thirdparty/' . $cate_symbol . '.php');
            $_zhushuyzclass = "thirdparty\\{$cate_symbol}";
            $_obj = new $_zhushuyzclass($arrs);

        }

        $res = $_obj->check();
        $dat = [
            'lt_self_commissionrate' => 0,
            'lt_trace_if' => 'no',
            'lt_trace_stop' => 'yes',
            "lt_issue_start" => $bets['round'],
            'lt_combuy_check' => 0
        ];
        $dat['OrderDataList'] = $res;
        $TraceDataList = [
            [
                'lt_trace_issues' => 1,
                'lt_trace_Times' => 0
            ]
        ];
        $dat['TraceDataList'] = $TraceDataList;
        $dat['userName'] = $app_info['username'];

        $url = $app_info['account_address'].'/api/external/lotterybetting/' . $lottery['third_lottery_id'];
        $time = TIME_NOW;
        $sign = md5($time . json_encode($dat) . 'ty25w3f8jkgg1xw633ypkg16');
        $header_sign = $sign . '_' . $time;
        $heades = [
            'X-Signature-Code:' . $header_sign,
        ];
        d($dat);
        $res = mycurl($url, json_encode($dat), 1, $heades);
        return json_decode($res, true);


    }


}

